﻿

// actionFlag: 1 -> 新增；2 -> 修改；3 -> 查看
var actionFlag = getPar1("actionFlag");
var const_UserId = parent.parent._currentUserID;
var const_UserName = parent.parent._currentUserName;

var accountsPayableData;

$(document).ready(function () {
    if (actionFlag == 1) {
        obj = $("#SystemGenNo");
        genNewSequenceNo(obj, "PaymentNo");

        $("#AddUserName").val(const_UserName);
        now = new Date();
        $("#AddTime").val(fnGetMyDate(now));
        $("#TotalAmount").val("0.00");

        $("#PaymentNo").focus();

        //$("#PayType").bind("change", function () { getBankAndAccountNo(); })
    }
});


// 检测付款单编号是否重复
var fnCheckPaymentNo = function (val) {
    if (val != "") {
        var paymentNo = fnGetData("BH_Payment", "ID<>'" + instance[0].ID.toString() + "' and PaymentNo='" + val + "'");
        if (paymentNo != null && paymentNo != "") {
            alert("付款单编号: [ " + val + " ] 已存在, 请重新输入!");
            setTimeout(function () {
                $("#PaymentNo").focus();
                $("#PaymentNo").val("");
            }, 10);
        }
    }
}

var getCompanyData = function (company) {
    return fnGetData("BH_Company", "CompanyNo='" + company + "' or CompanyName='" + company + "' or ShortName='" + company + "'");
}

// 设置供应商名称
var setCompanyName = function () {
    var companyNo = $("#CustomerNo").attr("SValue");
    Company = getCompanyData(companyNo);

    if (Company == null || Company == "") {
        alert("客户：" + companyNo + " 还未定义!");
        $("#CustomerName").val("");
        $("#CustomerNo").focus();
        return;
    }
    //加载客户相关的应付单
    if (getAccountPayableData(Company.rows[0].CompanyNo) == false) {
        accountsPayableData = "";
        $("#CustomerName").val("");
        $("#CustomerNo").focus();
        return;
    }

    $("#CustomerName").val(Company.rows[0].CompanyName);
    $("#Bank").val(Company.rows[0].Bank);
    $("#BankAccount").val(Company.rows[0].BankAccount);
}

// 支付方式为银行转账时自动调取厂家设置时的开户行与账号
var getBankAndAccountNo = function () {
    if ($("#PayType").val() == "BankTransfer") {
        customerNo = $("#CustomerNo").attr("SValue");
        customer = getCompanyData(customerNo);
        if (customer == null || customer == "") {
            return;
        }
        if ($("#Bank").val == "") {
            $("#Bank").val(customer.rows[0].Bank);
        }
        if ($("#BankAccount").val() == "") {
            $("#BankAccount").val(customer.rows[0].BankAccount);
        }
    }
}

//
var fnCustomeRowAddEvent = function (trs, i) {
    _DataTable.Rows[i].ID = "00000000-0000-0000-0000-000000000000";
    setLineNo();

    var factAmountObj = trs.find("input[name='FactAmount']");
    factAmountObj.numberbox({
        min: -999999999,
        precision: 2
    });
    factAmountObj.bind("change", function () { var t = $(this).val(); var o = trs; chkFactAmount(o, t); });
    //factAmountObj.bind("blur", function () { var t = $(this).val(); var o = trs; chkFactAmount(o, t); });
    factAmountObj.val("0.00");

    var o = trs.find("select[name='AccountsPayableNo']");
    setAPNoList(o, trs);
    o.focus();
}

// 加载客户的应付单号信息
var getAccountPayableData = function (customer) {
    accountsPayableData = fnGetData("V_BH_AccountsPayable", "VendorNo='" + customer + "' and FactAmount > PayedAmount");
    if (accountsPayableData == null || accountsPayableData == "") {
        alert("客户: " + customer + " 不存在相关应付单资料，不能进行付款操作!");
        setTimeout(function () {
            $("#CustomerNo").focus();
        }, 10);
        return false;
    }
    return true;
}

var setAPNoList = function (o, trs) {
    if (accountsPayableData == 0 || accountsPayableData == null) {
        return;
    }
    // 生成应付单列表
    //apNoList = trs.find("select[name='AccountsPayableNo']");
    apNoList = o;
    apNoList.get(0).options.length = 0;
    if (accountsPayableData.total > 0) {
        for (var i = 0; i < accountsPayableData.total; i++) {
            if (accountsPayableData.rows[i].AccountsPayableNo != undefined) {
                apNoList.append("<option value='" + accountsPayableData.rows[i].AccountsPayableNo + "'>" + accountsPayableData.rows[i].AccountsPayableNo + "</option>");
            }
        }
    }
    apNoList.bind("change", function () { var o = trs; getAPBal(o); });
    //apNoList.bind("blur", function () { var o = trs; getAPBal(o); });

    apNoList.get(0).options.selectedIndex = 0;
    apNoList.change();
}

var getAPBal = function (o) {
    customer = $("#CustomerNo").attr("SValue");
    apData = fnGetData("V_BH_AccountsPayable", "VendorNo='" + customer + "' and FactAmount > PayedAmount");
    if (apData == null || apData == "") {
        alert("客户: " + $("#CustomerName").val() + " 不存在相关应付单资料，不能进行付款操作!");
        setTimeout(function () {
            $("#CustomerNo").focus();
        }, 10);
        return;
    }
    //debugger;
    curValue = o.find("select[name='AccountsPayableNo']");
    accountsPayableNo = curValue.get(0).options[curValue.get(0).options.selectedIndex].value;
            

    for (var i = 0; i < apData.total; i++) {
        if (apData.rows[i].AccountsPayableNo == accountsPayableNo) {
            o.find("input[name='APFactAmount']").val(parseFloat(apData.rows[i].FactAmount).toFixed(2));
            o.find("input[name='APPayedAmount']").val(parseFloat(apData.rows[i].PayedAmount).toFixed(2));
            o.find("input[name='APNoFinishedAmount']").val((parseFloat(apData.rows[i].FactAmount) - parseFloat(apData.rows[i].PayedAmount)).toFixed(2));
        }
    }

    o.find("input[name='FactAmount']").focus();
}


// 检测录入的本次付款金额
var chkFactAmount = function (o, t) {
    //debugger;
    apFactAmount = o.find("input[name='APFactAmount']").val();
    apPayedAmount = o.find("input[name='APPayedAmount']").val();
    apNoFinishedAmount = o.find("input[name='APNoFinishedAmount']").val();

    if (apFactAmount > 0) {
        if ((parseFloat(t) > 0 && parseFloat(t) > parseFloat(apNoFinishedAmount)) || (parseFloat(t) < 0 && Math.abs(parseFloat(t)) > parseFloat(apPayedAmount))) {
            alert("输入本次付款金额出错! 金额范围应在：-" + apPayedAmount + " ~ " + apNoFinishedAmount + " 之间");
            setTimeout(function () {
                o.find("input[name='FactAmount']").focus();
                o.find("input[name='FactAmount']").val("0.00");
            }, 10);
            return;
        }
    }
    else if (apFactAmount < 0) {
        if ((parseFloat(t) > 0 && parseFloat(t) < Math.abs(parseFloat(apPayedAmount))) || (parseFloat(t) < 0 && (parseFloat(t)) > parseFloat(apNoFinishedAmount))) {
            alert("输入本次付款金额出错! 金额范围应在：" + apNoFinishedAmount + " ~ " + (Math.abs(parseFloat(apPayedAmount))).toString() + " 之间");
            setTimeout(function () {
                o.find("input[name='FactAmount']").focus();
                o.find("input[name='FactAmount']").val("0.00");
            }, 10);
            return;
        }
    }

    calcTotalFactAmount();
}

// 计算当前付款单的总金额
var calcTotalFactAmount = function () {
    var totalFactAmount = 0;
    var trs = $("#Details tbody tr");
    if (trs.length >= 1) {
        trs.each(function (em) {
            tmp = $(trs[em]).find("input[name='FactAmount']").val();
            totalFactAmount = totalFactAmount + parseFloat(tmp);
        });
    }
    totalAmount = (totalFactAmount == 0 ? "0.00" : totalFactAmount.toString());
    $("#TotalAmount").val(parseFloat(totalAmount).toFixed(2));
}


//
var fnCustomeRowDelEvent = function () {
    setLineNo();
}

var customSetEvent = function () {
    if (actionFlag == "2") {
        parent.setAddNewButtonHiden();
        //debugger;
        var trs = $("#Details tbody tr");
        if (trs.length >= 1) {
            trs.each(function (em) {
                $(trs[em]).find("select[name='AccountsPayableNo']").attr("disabled", "disabled");
                $(trs[em]).find("input[name='FactAmount']").attr("disabled", "disabled");
            });
        }

    }
}

var setLineNo = function () {
    var trs = $("#Details tbody tr");
    if (trs.length >= 1) {
        var seq = 1;
        trs.each(function (em) {
            $(trs[em]).find("input[name='LineNo']").val(seq.toString());
            seq = seq + 1;
        });
    }
}

// 检测付款明细
var fnCheckDetail = function () {
    var trs = $("#Details tbody tr");
    var errorFlag = 0;

    if (trs.length < 1) {
        alert("付款单不存在任何明细!");
        return false;
    }

    trs.each(function (em) {
        var apAccountsPayableNo = $(trs[em]).find("select[name='AccountsPayableNo']");
        var factAmount = $(trs[em]).find("input[name='FactAmount']");
        //debugger;
        if (apAccountsPayableNo.val() == "") {
            alert("明细表中应付单号不能为空!");
            apAccountsPayableNo.focus();
            errorFlag = 1;
            return false;
        }
        
        if (accountsPayableData.total > 0) {
            for (var i = 0; i < accountsPayableData.total; i++) {
                if (accountsPayableData.rows[i].AccountsPayableNo == apAccountsPayableNo.val()) {
                    //alert(accountsPayableData.rows[i].ID);
                    _DataTable.Rows[em].AccountsPayableID = accountsPayableData.rows[i].ID;
                }
            }
        }

        if (parseFloat(factAmount.val().toString()) == 0) {
            alert("明细表中本次应付金额不能为0!");
            factAmount.focus();
            errorFlag = 1;
            return false;
        }
    });

    if (errorFlag == 1) {
        return false;
    }

    return true;
}


// 提交检测
var fnCustomCheck = function () {
    if (instance[0].PaymentNo == "" || instance[0].PaymentNo == null) {
        $('#PaymentNo').focus();
        return "付款单编号不能为空!";
    }
    if (instance[0].CustomerNo == "" || instance[0].CustomerNo == null) {
        $('#CustomerNo').focus();
        return "客户不能为空!";
    }
    if (instance[0].PayDate == "" || instance[0].PayDate == null) {
        $('#PayDate').focus();
        return "付款日期不能为空!";
    }
    if (instance[0].PayType == "" || instance[0].PayType == null) {
        $('#PayType').focus();
        return "支付方式不能为空!";
    }
    if (instance[0].PayType == "BankTransfer" || instance[0].PayType == "Remittance") {
        if (instance[0].Bank == "" || instance[0].Bank == null) {
            $('#Bank').focus();
            return "开户银行不能为空!";
        }
        if (instance[0].BankAccount == "" || instance[0].BankAccount == null) {
            $('#BankAccount').focus();
            return "账户号码不能为空!";
        }
    }

    return "";
}

var fnSetValue = function () {
    instance[0].PaymentNo = instance[0].PaymentNo.toUpperCase();
    instance[0].AddUser = const_UserId;
}

// 保存数据
var fnCustomSave = function () {
    
    if (fnCheckDetail() == false) {
        return;
    }

    fnSetValue();

    dataAction = (actionFlag == "1") ? "A" : "C";
    //debugger;
    if (typeof (_DataTable) != "undefined") {
        if (fnCheckEmpty() == false) {
            alert("明细数据没有录入");
        }
        _DataTable.GetData();

        detailJson = $.toJSON(_DataTable.Rows).replace(/'/g, "[B]").replace(/\+/g, "[J]")
    }

    json = $.toJSON(instance[0]).replace(/'/g, "[B]").replace(/\+/g, "[J]");
    //debugger;
    //return;
    $.ajax({
        async: false, //异步请求
        cache: false, //不从浏览器缓存中加载
        type: "GET",
        /*dataType: "json",*/
        url: "/DCBH/DCBHCommonOperator.aspx",
        data: { Action: "procedure", entity: "V_BH_Payment", json: json, detailJson: detailJson, dataAction: dataAction },
        success: function (data) {
            //debugger;
            if (data != "") {
                if (data == "1") {
                    alert("数据保存成功!");

                    if (parent.SaveAndAddNewFlag == true) {
                        location.href = location.href
                    }

                    if (parent.SaveSuccessClose == true) {
                        parent.parent.CloseCurPage();
                    }
                }
                else {
                    alert(data);
                }
            }
        },
        error: function (e) {
            alert("保存失败, 请联系开发人员，核查系统！");
            return;
        }
    });

} 